﻿using System;
using System.Collections.Generic;
using System.Text;
using BoYuanCore.DBServices.Base;
using BoYuanCore.Framework.MemoryCache;

namespace BoYuanCore.DBServices
{
    public class SysModulePermissions
    {
        private const string cacheKey = nameof(Entities.SysModulePermissions);

        /// <summary>
        /// 从用户id获取权限角色，根据权限角色获取相关权限页面组件id
        /// </summary>
        /// <param name="userid"></param>
        /// <param name="_iCachingProvider"></param>
        /// <returns></returns>
        public static List<long> GetPermissionsByCache(long userid, ICachingProvider _iCachingProvider)
        {
            var admin = SysAdmin.GetAdminByCache(userid, _iCachingProvider);

            return _iCachingProvider.GetOrSetObjectFromCache(cacheKey + "_"+admin.RoleID, () =>
            {
                var db = FreeSqlHelper.GetInstance();
                return db.Select<Entities.SysModulePermissions,Entities.SysRole>()
                    .LeftJoin((p,r)=>p.RoleID==r.ID)
                    .Where((p, r) => p.RoleID == admin.RoleID && r.IsDel==false)
                    .ToList((p, r) => p.PageID);
            });
        }

        /// <summary>
        /// 根据权限角色，更新权限页面组件id缓存
        /// </summary>
        /// <param name="roleId">角色id</param>
        /// <param name="_iCachingProvider"></param>
        /// <returns></returns>
        public static void RemoveByCache(long roleId, ICachingProvider _iCachingProvider)
        {
            _iCachingProvider.Remove(cacheKey + "_" + roleId);
        }

    }
}
